package at.jku.ase.communication.parsers;

import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.util.HashMap;
import java.util.Map;

public class StanzaParser {
    private final Map<String, ComponentParser> delegates;

    public StanzaParser() {
        delegates = new HashMap<String, ComponentParser>();
    }

    public void parse(XMLStreamReader reader) throws XMLStreamException {
         for (int event = reader.next(); event != XMLStreamConstants.END_DOCUMENT; event = reader.next()) {
            if (event == XMLStreamConstants.START_ELEMENT) {
                String element = reader.getLocalName();
                System.out.println("Parsing Element: " + element);
                if (delegates.containsKey(element)) {
                    delegates.get(element).handle(reader);
                    delegates.remove(element);
                    if (delegates.size() == 0) {
                        return;
                    }
                }
            }
        } // rof
    }

    public void registerParser(String name, ComponentParser parser) {
        delegates.put(name, parser);
    }

}
